/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisy.tools;

import cz.mzk.oai.metadataRepository.repository.Identifier;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class ItemTransfer {

    private final MetadataCollection from;
    private final MetadataCollection to;
    private final List<Identifier> itemsToBeMoved = new ArrayList<Identifier>();
    private final static Map<MetadataCollection, Map<MetadataCollection, ItemTransfer>> fromMap = new HashMap<MetadataCollection, Map<MetadataCollection, ItemTransfer>>();

    public static ItemTransfer getTransfer(MetadataCollection from, MetadataCollection to) {
        Map<MetadataCollection, ItemTransfer> toMap = getFromMap(from);
        return getItemTransfer(toMap, to, from);
    }

    private static Map<MetadataCollection, ItemTransfer> getFromMap(MetadataCollection from) {
        Map<MetadataCollection, ItemTransfer> result = fromMap.get(from);
        if (result == null) {
            result = new HashMap<MetadataCollection, ItemTransfer>();
            fromMap.put(from, result);
        }
        return result;
    }

    private static ItemTransfer getItemTransfer(Map<MetadataCollection, ItemTransfer> toMap, MetadataCollection to, MetadataCollection from) {
        ItemTransfer transfer = toMap.get(to);
        if (transfer == null) {
            transfer = new ItemTransfer(from, to);
            toMap.put(to, transfer);
        }
        return transfer;
    }

    public static List<ItemTransfer> getAllTransfers() {
        List<ItemTransfer> result = new ArrayList<ItemTransfer>();
        for (Map<MetadataCollection, ItemTransfer> toMap : fromMap.values()) {
            for (ItemTransfer transfer : toMap.values()) {
                result.add(transfer);
            }
        }
        return result;
    }

    public ItemTransfer(MetadataCollection from, MetadataCollection to) {
        this.from = from;
        this.to = to;
    }

    public void addIdentifier(Identifier id) {
        itemsToBeMoved.add(id);
    }

    /**
     * @return the from
     */
    public MetadataCollection getFrom() {
        return from;
    }

    /**
     * @return the to
     */
    public MetadataCollection getTo() {
        return to;
    }

    /**
     * @return the itemsToBeMoved
     */
    public List<Identifier> getItemsToBeMoved() {
        return itemsToBeMoved;
    }

    void writeTo(PrintWriter out) {
        out.println("FROM_COLLECTION:" + from.getName());
        out.println("TO_COLLECTION:" + to.getName());
        for (Identifier id : itemsToBeMoved) {
            out.println(id.toString());
        }
        out.flush();
    }
}
